package com.code.aspectj.aspectj;

import android.text.TextUtils;

import com.code.aspectj.AppInterceptor;
import com.code.aspectj.annotation.Safe;
import com.code.aspectj.util.ReflectUtils;
import com.code.aspectj.util.P;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import static com.code.aspectj.AppInterceptor.TAG;

/**
 * Created by RLZ
 * on 2021/12/8
 * 处理异常切片
 */
@Aspect
public class SafeAspect {

    @Pointcut("within(@com.code.aspectj.annotation.Safe *)")
    public void withinAnnotatedClass() {
    }

    @Pointcut("execution(!synthetic * *(..)) && withinAnnotatedClass()")
    public void methodInsideAnnotatedType() {
    }

    @Pointcut("execution(@com.code.aspectj.annotation.Safe * *(..)) || methodInsideAnnotatedType()")
    public void method() {
    }  //方法切入点

    @Around("method() && @annotation(safe)")//在连接点进行方法替换
    public Object aroundJoinPoint(final ProceedingJoinPoint joinPoint, Safe safe) {
        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            //异常情况 如果有flag 用户处理 如果没有 则不处理
            if (AppInterceptor.getSafeHandler() != null) {
                String flag = safe.value();
                if (TextUtils.isEmpty(flag)) {
                    flag = ReflectUtils.getMethodName(joinPoint);
                }
                result = AppInterceptor.getSafeHandler().handleThrowable(flag, e);
            } else {
                P.e(TAG,e); //默认不做任何处理
            }
        }
        return result;
    }
}
